﻿Public Class Hitori
    Inherits Puzzle

    Public Overrides Function OnKeyPress(ByVal Key As String) As Boolean
        Select Case Key
            Case "0" To "9"
                CursorCell.g = Key
            Case "delete"
                CursorCell.g = " "
            Case Else
                Return MyBase.OnKeyPress(Key)
        End Select
    End Function

    Public Overrides Sub Load(ByVal Data As String)
        Size = Math.Sqrt(Len(Data))
        NewPuzzle()
        For k = 0 To Size * Size - 1
            Cells(k).g = Data(k)
        Next
        Invalidate()
    End Sub

    Public Overrides Function Save() As String
        Dim Text As String = ""
        For i As Integer = 1 To Size * Size
            Dim Cell As Cell = Cells(i - 1)
            Text &= Cell.g
        Next
        Return Text
    End Function

    Public Overrides Sub Solve()
        ClearLog()
        For Each Cell In Cells
            Cell.f = ""
        Next
        'For Each Result In (From g In Groups
        '                  From c1 In g.Cells From c2 In g.Cells Where g.IndexOf(c1) + 1 = g.IndexOf(c2)
        '                  From c3 In g.Cells Where c3.g = c1.g And g.IndexOf(c2) + 1 = g.IndexOf(c3) And c2.f = "").ToList
        '    Result.c2.f = "x"
        'Next
        For Each Result In (From g In Groups From c1 In g.Cells Where (From c2 In g.Cells Where Not c1 Is c2 And c2.g = c1.g And c2.f = "x").Any).ToList
            Result.c1.f = "*"
        Next
        For Each Cl In From c1 In Cells From c2 In Cells Where c1.f = "*" And Math.Abs(c1.x - c2.x) + Math.Abs(c1.y - c2.y) = 1 And c2.f = ""
            Cl.c2.f = "x"
        Next
        Invalidate()
    End Sub

    Public Sub New()
        AvailableSizes = Enumerable.Range(6, 5).ToList
        Size = 8
    End Sub

    Public Overrides Sub DrawCell(ByVal e As DrawCellArgs)
        e.Invert = e.Cell.f = "*"
        e.Circled = e.Cell.f = "x"
        MyBase.DrawCell(e)
    End Sub

End Class
